package com.atguigu.flink.chapter08;

import com.atguigu.flink.bean.HotItem;
import com.atguigu.flink.bean.UserBehavior;
import com.atguigu.flink.util.AtguiguUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/10/19 9:12
 */
public class Flink03_Project_High_TopN {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        
        env
            .readTextFile("input/UserBehavior.csv")
            .map(line -> {
                String[] data = line.split(",");
                return new UserBehavior(Long.valueOf(data[0]),
                                        Long.valueOf(data[1]),
                                        Integer.valueOf(data[2]),
                                        data[3],
                                        Long.parseLong(data[4]) * 1000);
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((ub, ts) -> ub.getTimestamp())
            )
            .filter(ub -> "pv".equals(ub.getBehavior()))
            //            .keyBy(ub -> ub.getItemId())
            .keyBy(UserBehavior::getItemId)
            .window(SlidingEventTimeWindows.of(Time.hours(1), Time.minutes(30)))
            .aggregate(
                new AggregateFunction<UserBehavior, Long, Long>() {
                    @Override
                    public Long createAccumulator() {
                        return 0L;
                    }
                    
                    @Override
                    public Long add(UserBehavior value, Long accumulator) {
                        return accumulator + 1;
                    }
                    
                    @Override
                    public Long getResult(Long accumulator) {
                        return accumulator;
                    }
                    
                    @Override
                    public Long merge(Long a, Long b) {
                        return null;
                    }
                },
                new ProcessWindowFunction<Long, HotItem, Long, TimeWindow>() {
                    @Override
                    public void process(Long key,
                                        Context ctx,
                                        Iterable<Long> elements,
                                        Collector<HotItem> out) throws Exception {
                        
                        out.collect(new HotItem(key, ctx.window().getEnd(), elements.iterator().next()));
                    }
                }
            )
            .keyBy(HotItem::getWEnd)
            .process(new KeyedProcessFunction<Long, HotItem, String>() {
                
                private ListState<HotItem> hotItemState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    // f + alt + ctrl
                    hotItemState = getRuntimeContext()
                        .getListState(new ListStateDescriptor<HotItem>("hotItemState", HotItem.class));
                }
                
                @Override
                public void processElement(HotItem hotItem,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    // 每来一条数据, 把数据存入到状态, 等到定时器触发的时候, 进行排序
                    if (!hotItemState.get().iterator().hasNext()) {
                        // 现在是来了第一条数据: 注册定时器
                        ctx.timerService().registerEventTimeTimer(hotItem.getWEnd() + 5000);
                    }
                    
                    hotItemState.add(hotItem);
                    
                }
                
                // ctrl + o
                @Override
                public void onTimer(long timestamp,
                                    OnTimerContext ctx,
                                    Collector<String> out) throws Exception {
                    List<HotItem> hotItems = AtguiguUtil.toList(hotItemState.get());
                    
                    // java的排序一般是就地排序
                    hotItems.sort((o1, o2) -> o2.getCount().compareTo(o1.getCount()));
                    
                    StringBuilder sb = new StringBuilder();
                    sb.append("-----------------\n");
                    for (int i = 0, count = Math.min(3, hotItems.size()); i < count; i++) {
                        sb.append(hotItems.get(i)).append("\n");
                    }
                    out.collect(sb.toString());
                }
            })
            .print();
        
        env.execute();
    }
}
